package com.ympc.service.impl;

import com.ympc.mapper.UsersMapper;
import com.ympc.pojo.Users;
import com.ympc.service.UsersService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

@Service
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersMapper usersMapper;

    @Override
    public Integer login(Users users, HttpSession session) {
        Users u=usersMapper.login(users);
        if(u!=null){
            if(u.getPassword().equals(users.getPassword())){
                if(u.getRole().equals(users.getRole())){
                    session.setAttribute("user",u);
                    return 1;
                }
                return 3;
            }else {
                return 2;
            }
        }
        return 0;
    }
    
    @Override
    public Users createUser(String username, String password, String rlname, String role) {
        // 检查用户名是否已存在
        Users existingUser = usersMapper.findByUsername(username);
        if (existingUser != null) {
            return existingUser; // 如果已存在，返回现有用户
        }
        
        // 创建新用户
        Users newUser = new Users();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setRlname(rlname);
        newUser.setRole(role);
        
        int result = usersMapper.insertUser(newUser);
        if (result > 0) {
            // 重新查询获取生成的ID
            return usersMapper.findByUsername(username);
        }
        return null;
    }
    
    @Override
    public Users getUserByUsername(String username) {
        return usersMapper.findByUsername(username);
    }
    
    @Override
    public Users getUserByRlnameAndRole(String rlname, String role) {
        return usersMapper.findByRlnameAndRole(rlname, role);
    }
    
    @Override
    public Users loginByUsernameOrName(String usernameOrName, String role) {
        // 先尝试作为用户名（学号）查询
        Users user = usersMapper.findByUsername(usernameOrName);
        if (user != null && user.getRole().equals(role)) {
            return user;
        }
        
        // 如果用户名查询失败，尝试作为真实姓名查询
        user = usersMapper.findByRlnameAndRole(usernameOrName, role);
        return user;
    }
}
